﻿using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WPF.Core
{
    public class HostDialogViewModel : BindableBase, IHostDialogAware
    {
        public HostDialogViewModel()
        {
            SaveCommand = new DelegateCommand(Save);
            CancelCommand = new DelegateCommand(Cancel);
        }
        private bool isBusy;

        public bool IsBusy
        {
            get { return isBusy; }
            set { isBusy = value;  RaisePropertyChanged(); }
        }

        public string identifier { get; set; }

        public string Title { get; set; } = "";

        public DelegateCommand SaveCommand { get; private set; }

        public DelegateCommand CancelCommand { get;private set; }

        public event Action<IDialogResult> RequestClose;



        public virtual bool CanCloseDialog()
        {
          return true;
        }

        public void OnDialogClosed()
        {
            //RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
            if (DialogHost.IsDialogOpen(identifier))
            {
                DialogHost.Close(identifier, new DialogResult(ButtonResult.OK));
            }
        }

        public virtual void OnDialogOpened(IDialogParameters parameters)
        {
           
        }


        private void Cancel()
        {
            // RequestClose?.Invoke(new DialogResult(ButtonResult.No));
            if (DialogHost.IsDialogOpen(identifier))
            {
                DialogHost.Close(identifier, new DialogResult(ButtonResult.No));
            }
        }

        public virtual void Save()
        {
            //RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
            if (DialogHost.IsDialogOpen(identifier))
            {
                DialogHost.Close(identifier, new DialogResult(ButtonResult.OK));
            }
        }

        /// <summary>
        /// 执行等待任务
        /// </summary>
        /// <param name="func"></param>
        public async Task SetBusyAsync(Func<Task> func)
        {
            if (IsBusy) return;
            try
            {
                IsBusy = true;
                await func();
            }
            finally
            {
                IsBusy =false;
            }
        }
    }
}
